package org.example.shop.dao;

import org.example.shop.pojo.Goods;
import org.hibernate.annotations.Parameter;
import org.hibernate.annotations.SQLUpdate;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

@Repository
public interface GoodsDao extends JpaRepository<Goods, Integer> {
    /**
     * 更新会有行锁
     * @param id
     * @param count
     * @return 返回SQL执行后 受影响的行数(如果库存不足 受影响行数为0)
     */
    @Transactional
    @Modifying
    @Query(nativeQuery = true, value = "update goods set stock=stock - ?2 where id=?1 and stock >= ?2")
    int deductCount(@Param("id") Integer id, @Param("count") int count);
}
